package com.haoshuang.zhouzhoubang.ui.page.main

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import cn.jpush.android.api.JPushInterface
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.PermissionUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityMainBinding
import com.haoshuang.zhouzhoubang.model.bean.CooperationTimeBean
import com.haoshuang.zhouzhoubang.model.event.HomeJumpOrderIndexPageEvent
import com.haoshuang.zhouzhoubang.model.event.LogoutEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshTeamUserInfo
import com.haoshuang.zhouzhoubang.services.MyWorkService
import com.haoshuang.zhouzhoubang.ui.activity.FeedBackActivity
import com.haoshuang.zhouzhoubang.ui.activity.OrderWcActivity
import com.haoshuang.zhouzhoubang.ui.activity.PushOrder2Activity
import com.haoshuang.zhouzhoubang.ui.activity.ServiceLogActivity2
import com.haoshuang.zhouzhoubang.ui.activity.ZsmActivity
import com.haoshuang.zhouzhoubang.ui.adapter.ViewPagerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.CallDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.NoticePushDialog
import com.haoshuang.zhouzhoubang.ui.dialog.UpdateVersionDialog
import com.haoshuang.zhouzhoubang.ui.page.account.login.LoginActivity
import com.haoshuang.zhouzhoubang.ui.page.home.HomeFragment
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.add.AddSkillListActivity
import com.haoshuang.zhouzhoubang.ui.page.message.MessageFragment
import com.haoshuang.zhouzhoubang.ui.page.mine.MineFragment
import com.haoshuang.zhouzhoubang.ui.page.mine.contract.MyContractActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.info.MineUserInfoActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.integral.StoreIntegralActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.notice.publish.PublishNoticeActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.settings.SettingsActivity
import com.haoshuang.zhouzhoubang.ui.page.order.OrderFragment
import com.haoshuang.zhouzhoubang.ui.page.settled.pay.AnnualFeePayActivity
import com.haoshuang.zhouzhoubang.ui.page.shop.ShoppingActivity
import com.haoshuang.zhouzhoubang.ui.page.study.StudyFragment
import com.haoshuang.zhouzhoubang.ui.page.welfare.PlatformWelfareHomeActivity
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.ktx.toDateForm
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import java.util.Date


/**
 *  主页面
 */
class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<MainActivity>()
        }
    }

    private val fragments = arrayListOf<Fragment>()
    private lateinit var orderFragment: OrderFragment
    private lateinit var studyFragment: StudyFragment
    private lateinit var messageFragment: MessageFragment
    private lateinit var mineFragment: MineFragment

    // 合作期限列表
    private val cooperationTimeList = arrayListOf<CooperationTimeBean>()

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent != null) {
            val index = intent.getString("index")
            val indexs = index.split("-").filter { it.isNotEmpty() }
            if (indexs.isNotEmpty()) {
                binding.viewPager.currentItem = indexs[0].toInt()
                if (indexs[0].toInt() == 2) {
                    (fragments[2] as MessageFragment).showIndex(indexs[2].toInt())
                }else if (indexs[0].toInt() == 3) {
                    startOrderPage(3)
                }
            }
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        binding.drawerLayout.setDrawerLockMode(
            DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
            GravityCompat.START
        )
        orderFragment = OrderFragment.getInstance()
//        homeFragment = HomeFragment.getInstance()
        studyFragment = StudyFragment.getInstance()
        messageFragment = MessageFragment.getInstance()
        mineFragment = MineFragment.getInstance()
//        fragments.add(homeFragment)
        fragments.add(orderFragment)
        fragments.add(studyFragment)
        fragments.add(messageFragment)
        fragments.add(mineFragment)

        val adapter = ViewPagerAdapter(supportFragmentManager, lifecycle, fragments)
        binding.viewPager.adapter = adapter
        binding.viewPager.isUserInputEnabled = false
        binding.viewPager.offscreenPageLimit = 4

        binding.bblMain.setOnItemSelectedListener { bottomBarItem, previousPosition, currentPosition ->

            binding.viewPager.setCurrentItem(currentPosition, false)
            when (currentPosition) {
                0 -> {
                    immersionBar {
                        statusBarDarkFont(false) //状态栏字体 true为深色 false为亮色
                        statusBarColor(R.color.c_FF101626)   //设置状态栏颜色
                        titleBarMarginTop(binding.root)
                    }
                    (fragments[0] as OrderFragment).refreshData()
                }

                1 -> {
                    immersionBar {
                        statusBarDarkFont(true) //状态栏字体 true为深色 false为亮色
                        statusBarColor(R.color.white)   //设置状态栏颜色
                        titleBarMarginTop(binding.root)
                    }
                }

                2 -> {
                    immersionBar {
                        statusBarDarkFont(true) //状态栏字体 true为深色 false为亮色
                        statusBarColor(R.color.white)   //设置状态栏颜色
                        titleBarMarginTop(binding.root)
                    }
                }

                3 -> {
                    immersionBar {
                        statusBarDarkFont(false) //状态栏字体 true为深色 false为亮色
                        statusBarColor(R.color.c_10)   //设置状态栏颜色
                        titleBarMarginTop(binding.root)
                    }
                }
            }
        }

        binding.ivClose.click {
            binding.drawerLayout.close()
        }

        binding.tvCode.click {
            // 打开专属码
            startPage<ZsmActivity>()
        }

        binding.tvSettings.click {
            // 设置
            startPage<SettingsActivity>()
        }

        // 编辑资料
        binding.tvEdit.click {
            startPageForResult<MineUserInfoActivity> { code, data ->
                if (code == 200) {
                    vm.getStoreUserInfo()
                }
            }
        }

        // 续费
        binding.tvRenew.click {
            // 续费
            vm.getCooperationPeriod(AccountUtils.user?.city_name)
        }

        // 推送订单
        binding.llPushOrder.click {
            // 推送订单
            startPage<PushOrder2Activity>()
        }

        // 服务订单
        binding.llServiceOrder.click {
            // 服务订单
            startPage<OrderWcActivity>()
        }

        // 评价记录
        binding.tvCommentRecord.click {
            // 评价记录
            startPage<ServiceLogActivity2>()
        }

        // 门店积分
        binding.llStorePoints.click {
            startPage<StoreIntegralActivity>()
        }

        // 服务类别
        binding.llSkillCenter.clickWithTrigger {
            startPage<AddSkillListActivity>()
        }

        // 我的合同
        binding.llMineContract.click {
            // 我的合同
            startPage<MyContractActivity>()
        }

        // 意见反馈
        binding.llFeedback.click {
            // 意见反馈
            startPage<FeedBackActivity>()
        }

        // 联系客服
        binding.llContactService.click {
            // 联系客服
            if (MyApp.systemConfig?.tel.isNullOrBlank()) {
                toast("客服没有留电话,暂时无法拨打")
                return@click
            }

            XPopup.Builder(mActivity)
                .asCustom(CallDialog(mActivity, MyApp.systemConfig?.tel ?: "") {
                    var intent = Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:${MyApp.systemConfig?.tel}"));
                    startActivity(intent);
                })
                .show()
        }

        // 发布公告
        binding.llPublishNotice.click {
            // 发布公告
            startPage<PublishNoticeActivity>()
        }

        // 商城中心
        binding.llShop.clickWithTrigger {
            startPage<ShoppingActivity>()
        }

        // 平台福利
        binding.llPlatformGift.click {
            // 平台福利
            startPage<PlatformWelfareHomeActivity>()
        }

        if (intent != null) {
            val index = intent.getString("index")
            val indexs = index.split("-").filter { it.isNotEmpty() }
            if (indexs.isNotEmpty()) {
                binding.viewPager.currentItem = indexs[0].toInt()
                if (indexs[0].toInt() == 2) {
                    (fragments[2] as MessageFragment).showIndex(indexs[2].toInt())
                }
            }
        }

    }

    /**
     * 显示侧滑菜单
     */
    fun showDrawerLayout() {
        if (AccountUtils.user?.status == "8") {
            binding.drawerLayout.open()
        } else {
            XPopup.Builder(mActivity)
                .asCustom(
                    ConfirmDialog(
                        context = mActivity,
                        title = "温馨提示",
                        content = "您还未入驻, 请先入驻, 或切换账号",
                        cancelStr = "继续入驻",
                        confirmStr = "切换账号",
                        isHideCancel = false,
                        onCancel = {},
                        onConfirm = {
                            ActivityUtils.getTopActivity().startPage<LoginActivity>()
                            ActivityUtils.finishOtherActivities(LoginActivity::class.java)
                            AccountUtils.logout()
                            LiveEventBus.get(LogoutEvent::class.java).post(LogoutEvent)
                        })
                )
                .show()
        }
    }

    override fun initData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PermissionUtils.permission(Manifest.permission.POST_NOTIFICATIONS)
                .callback { isAllGranted, granted, deniedForever, denied ->
                    if (isAllGranted) {
                        startMyWorkService()
                    }
                }.request()
        } else {
            startMyWorkService()
        }
        initPush()
        vm.getAppVersions()

    }

    private fun initPush() {
        if (!AccountUtils.isAgreeNotification) {
            XPopup.Builder(mActivity)
                .asCustom(NoticePushDialog(mActivity) {
                    AccountUtils.isAgreeNotification = true
                    setAlias(AccountUtils.user?.uid.toString())
//                    (fragments[0] as HomeFragment).showGuide()
                })
                .show()
        } else {
            setAlias(AccountUtils.user?.uid.toString())
//            (fragments[0] as HomeFragment).showGuide()
        }
    }

    /**
     * 设置推送别名
     * @param alias String
     */
    private fun setAlias(alias: String) {

        var alias1 = alias
        if (Config.isTestEnvironment) {
            if (AccountUtils.isTestEnvironment) {
                alias1 = "${alias1}_dev"
            } else {
                alias1 = "${alias1}_online"
            }
        } else {
            alias1 = "${alias1}_online"
        }
        JPushInterface.setAlias(mActivity, alias.toIntOrNull() ?: 1, alias1)
    }

    private fun startMyWorkService() {
        val service = Intent(this, MyWorkService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(service)
        } else {
            startService(service)
        }
    }

    override fun onResume() {
        super.onResume()
        vm.getSystemConfig()
        vm.getStoreUserInfo()
    }

    private fun setMineData() {
        val user = AccountUtils.user
        val team = user?.team
        if (user?.status == "8") {
            binding.rivHead.load(
                team?.team_logo,
                placeholder = R.mipmap.logo,
                error = R.mipmap.logo
            )
            binding.tvName.text = team?.team_name
        } else {
            binding.rivHead.load(
                user?.avatar,
                placeholder = R.mipmap.logo,
                error = R.mipmap.logo
            )
            binding.tvName.text = user?.nickname
        }
        if (team?.team_name.isNullOrEmpty() || team?.team_logo.isNullOrEmpty() || user?.team_company_pic.isNullOrEmpty() || user?.synopsis.isNullOrEmpty()) {
            binding.tvEdit.text = "待完善"
        } else {
            binding.tvEdit.text = "去编辑"
        }

        if (team?.team_end_time?.isNotEmpty() == true) {
            binding.llTeamTime.visible()
            val end = team.team_end_time.toDateForm("yyyy-MM-dd")!!
            val now = Date()
            if (end.time > now.time) {
                binding.tvExpirationTime.text = "门店到期时间: ${team?.team_end_time}"
            } else {
                binding.tvExpirationTime.text = "门店已到期"
            }
            binding.tvRenew.text = "续费"
        } else {
            binding.llTeamTime.gone()
        }

        // 推送订单数
        binding.tvPushOrderNum.text = team?.tui_order_num.toString()
        // 服务订单数
        binding.tvServiceOrderNum.text = team?.complete_order_num.toString()
        // 免服务费
        binding.tvServiceFeeOrderNum.text = team?.fee_order_num.toString()
        // 积分
        binding.tvStorePoints.text = team?.team_integral.toString()

    }

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(false) //状态栏字体 true为深色 false为亮色
            statusBarColor(R.color.c_FF101626)   //设置状态栏颜色
            titleBarMarginTop(binding.root)
        }
    }

    override fun startObserve() {
        LiveEventBus.get(RefreshTeamUserInfo::class.java).observe(this) {
            vm.getStoreUserInfo()
        }

        vm.getCooperationPeriodData.observeState(this) {
            onSuccess {
                cooperationTimeList.clear()
                cooperationTimeList.addAll(it?.data ?: mutableListOf())
                if (cooperationTimeList.isNotEmpty()) {
                    XPopup.Builder(mActivity)
                        .asBottomList(
                            "选择合作期限",
                            cooperationTimeList.map { "${it.exp} - ${it.join_year}年/${it.join_money}元" }
                                .toTypedArray()
                        ) { position, text ->
                            val year = cooperationTimeList[position].join_year
                            val yearMoney = cooperationTimeList[position].join_money
                            startPage<AnnualFeePayActivity>(
                                "year" to year,
                                "fee" to yearMoney.toString()
                            )
                        }
                        .show()
                }
            }
        }

        // 获取门店用户信息
        vm.getStoreUserInfoData.observeState(this) {
            onLoading { }
            onError { code, msg -> }
            onSuccess {
                AccountUtils.user = it?.data
                setMineData()
                if (it?.data?.status == "8") {
                    vm.getMessageCount()
                }
            }
        }

        vm.getMessageCountData.observeState(this) {
            onSuccess {
                val data = it?.data
                val totalCount = (data?.system_msg?.count ?: 0) + (data?.team_msg?.count
                    ?: 0) + (data?.order_msg?.count ?: 0) + (data?.feedback_msg_count?.count ?: 0)
                setMessageUnReadCount(totalCount)
            }
        }

        vm.getAppVersionsData.observeState(this) {
            onSuccess {
                if (it != null) {
                    val manager = DownloadManager.Builder(mActivity).run {
                        apkUrl(it.android_download_url!!)
                        apkName("zhouzhoubang.apk")
                        smallIcon(R.mipmap.logo)
                        showNewerToast(false)
                        apkVersionCode(it.versions_code!!)
                        apkVersionName("V ${it.versions_no}")
                        apkDescription(it.content!!)
                        enableLog(true)
                        jumpInstallPage(true)
                        dialogButtonTextColor(Color.WHITE)
                        showNotification(true)
                        showBgdToast(true)
                        forcedUpgrade(it.is_force == 1)
                        build()
                    }
                    manager.download()
                }
            }
        }

        vm.getSystemConfigData.observeState(this) {
            onSuccess { MyApp.systemConfig = it?.data }
        }

    }

    override fun onBackPressed() {
        if (binding.bblMain.currentItem == 0) {
            doubleBackToFinish { ActivityUtils.finishAllActivities() }
        } else {
            binding.bblMain.currentItem = 0
        }

    }

    /**
     * 设置消息未读数量
     * @param count Int
     */
    fun setMessageUnReadCount(count: Int) {
        if (count > 0) {
            binding.bbiMessage.showNotify()
        } else {
            binding.bbiMessage.hideNotify()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService(Intent(this, MyWorkService::class.java))
    }

    fun startStudyPage() {
        binding.bblMain.currentItem = 1
    }

    fun startOrderPage(index: Int) {
        binding.bblMain.currentItem = 0
        LiveEventBus.get(HomeJumpOrderIndexPageEvent::class.java)
            .post(HomeJumpOrderIndexPageEvent(index))
    }

}